<?php
if (!defined('SMF'))
	die('Hacking attempt...');

global $db_prefix;
global $bnt_db_prefix;	

//Log constants
define("LOG_LOGIN", 1);
define("LOG_LOGOUT", 2);
define("LOG_ATTACK_OUTMAN", 3);           //sent to target when better engines
define("LOG_ATTACK_OUTSCAN", 4);          //sent to target when better cloak
define("LOG_ATTACK_EWD", 5);              //sent to target when EWD engaged
define("LOG_ATTACK_EWDFAIL", 6);          //sent to target when EWD failed
define("LOG_ATTACK_LOSE", 7);             //sent to target when he lost
define("LOG_ATTACKED_WIN", 8);            //sent to target when he won
define("LOG_TOLL_PAID", 9);               //sent when paid a toll
define("LOG_HIT_MINES", 10);              //sent when hit mines
define("LOG_SHIP_DESTROYED_MINES", 11);   //sent when destroyed by mines
define("LOG_PLANET_DEFEATED_D", 12);      //sent when one of your defeated planets is destroyed instead of captured
define("LOG_PLANET_DEFEATED", 13);        //sent when a planet is defeated
define("LOG_PLANET_NOT_DEFEATED", 14);    //sent when a planet survives
define("LOG_RAW", 15);                    //this log is sent as-is
define("LOG_TOLL_RECV", 16);              //sent when you receive toll money
define("LOG_DEFS_DESTROYED", 17);         //sent for destroyed sector defenses
define("LOG_PLANET_EJECT", 18);           //sent when ejected from a planet due to alliance switch
define("LOG_BADLOGIN", 19);               //sent when bad login
define("LOG_PLANET_SCAN", 20);            //sent when a planet has been scanned
define("LOG_PLANET_SCAN_FAIL", 21);       //sent when a planet scan failed
define("LOG_PLANET_CAPTURE", 22);         //sent when a planet is captured
define("LOG_SHIP_SCAN", 23);              //sent when a ship is scanned
define("LOG_SHIP_SCAN_FAIL", 24);         //sent when a ship scan fails
define("LOG_XENOBE_ATTACK", 25);			//xenobes send this to themselves
define("LOG_STARVATION", 26);             //sent when colonists are starving... Is this actually used in the game?
define("LOG_TOW", 27);                    //sent when a player is towed
define("LOG_DEFS_DESTROYED_F", 28);       //sent when a player destroys fighters
define("LOG_DEFS_KABOOM", 29);            //sent when sector fighters destroy you
define("LOG_HARAKIRI", 30);               //sent when self-destructed
define("LOG_TEAM_REJECT", 31);            //sent when player refuses invitation
define("LOG_TEAM_RENAME", 32);            //sent when renaming a team
define("LOG_TEAM_M_RENAME", 33);          //sent to members on team rename
define("LOG_TEAM_KICK", 34);              //sent to booted player
define("LOG_TEAM_CREATE", 35);            //sent when created a team
define("LOG_TEAM_LEAVE", 36);             //sent when leaving a team
define("LOG_TEAM_NEWLEAD", 37);           //sent when leaving a team", appointing a new leader
define("LOG_TEAM_LEAD", 38);              //sent to the new team leader
define("LOG_TEAM_JOIN", 39);              //sent when joining a team
define("LOG_TEAM_NEWMEMBER", 40);         //sent to leader on join
define("LOG_TEAM_INVITE", 41);            //sent to invited player
define("LOG_TEAM_NOT_LEAVE", 42);         //sent to leader on leave
define("LOG_ADMIN_HARAKIRI", 43);         //sent to admin on self-destruct
define("LOG_ADMIN_PLANETDEL", 44);        //sent to admin on planet destruction instead of capture
define("LOG_DEFENCE_DEGRADE", 45);        //sent sector fighters have no supporting planet
define("LOG_PLANET_CAPTURED", 46);		//sent to player when he captures a planet
define("LOG_BOUNTY_CLAIMED",47);			//sent to player when they claim a bounty
define("LOG_BOUNTY_PAID",48);				//sent to player when their bounty on someone is paid
define("LOG_BOUNTY_CANCELLED",49);		//sent to player when their bounty is refunded
define("LOG_SPACE_PLAGUE",50);            // sent when space plague attacks a planet
define("LOG_PLASMA_STORM",51);            // sent when a plasma storm attacks a planet
define("LOG_BOUNTY_FEDBOUNTY",52);        // Sent when the federation places a bounty on a player
define("LOG_PLANET_BOMBED",53);			//Sent after bombing a planet
define("LOG_ADMIN_ILLEGVALUE", 54);       //sent to admin on planet destruction instead of capture

// Database tables variables
$dbtables['ibank_accounts'] = $db_prefix . $bnt_db_prefix . "ibank_accounts";
$dbtables['links'] = $db_prefix . $bnt_db_prefix . "links";
$dbtables['planets'] = $db_prefix . $bnt_db_prefix . "planets";
$dbtables['traderoutes'] = $db_prefix . $bnt_db_prefix . "traderoutes";
$dbtables['news'] = $db_prefix . $bnt_db_prefix . "news";
$dbtables['ships'] = $db_prefix . $bnt_db_prefix . "ships";
$dbtables['teams'] = $db_prefix . $bnt_db_prefix . "teams";
$dbtables['universe'] = $db_prefix . $bnt_db_prefix . "universe";
$dbtables['zones'] = $db_prefix . $bnt_db_prefix . "zones";
$dbtables['messages'] = $db_prefix . $bnt_db_prefix . "messages";
$dbtables['xenobes'] = $db_prefix . $bnt_db_prefix . "xenobes";
$dbtables['sector_defence'] = $db_prefix . $bnt_db_prefix . "sector_defence";
$dbtables['scheduler'] = $db_prefix . $bnt_db_prefix . "scheduler";
$dbtables['ip_bans'] = $db_prefix . $bnt_db_prefix . "ip_bans";
$dbtables['IGB_transfers'] = $db_prefix . $bnt_db_prefix . "IGB_transfers";
$dbtables['logs'] = $db_prefix . $bnt_db_prefix . "logs";
$dbtables['bounty'] = $db_prefix . $bnt_db_prefix . "bounty";
$dbtables['movement_log'] = $db_prefix . $bnt_db_prefix . "movement_log";
$dbtables['config'] = $db_prefix . $bnt_db_prefix . "config";

function mypw($one, $two)
{
	return pow($one * 1, $two * 1);
}

function BigTitle($title, $showlink = true)
{
	global $txt, $smcFunc;
	global $dbtables, $user_info;
	
	if ($showlink)
	{
		// Find out if they are on a planet or not
		$result = $smcFunc['db_query']('', '
			SELECT on_planet, planet_id
			FROM {raw:db_ships}
			WHERE user_id = {int:user_id}
			LIMIT 1',
			array(
				'db_ships' => $dbtables['ships'],
				'user_id' => $user_info['id'],
			)
		);
		$playerinfo = $smcFunc['db_fetch_assoc']($result);
		$smcFunc['db_free_result']($result);
		
		if ($playerinfo['on_planet'] == 'Y')
			echo '
					<input id="on_planet_id" type="hidden" value="', $playerinfo['planet_id'], '" />
					<div id="planet_display_frame"><span class="bnt_button ui-state-default ui-corner-all">', $txt['bnt_global_planet_display'], '</span></div>';
		else
			echo '
					<div id="sector_display_frame"><span class="bnt_button ui-state-default ui-corner-all">', $txt['bnt_global_sector_display'], '</span></div>';
	}
	
	if (isset($title))
		echo '
					<h1 class="bnt_title">', $title, '</h1>';
}

function TextMainMenu()
{
	global $scripturl, $txt;
	
	$txt['bnt_global_menu'] = str_replace("[scripturl]", $scripturl, $txt['bnt_global_menu']);
	echo '<p>', $txt['bnt_global_menu'], '</p>';
}

function TextPlayerNotFound()
{
	global $scripturl, $txt;
	
	$txt['bnt_global_nochar'] = str_replace("[scripturl]", $scripturl, $txt['bnt_global_nochar']);
	echo '
		<p>', $txt['bnt_global_nochar'], '</p>';
}

function TEXT_JAVASCRIPT_BEGIN()
{
	echo '<script language="javascript">';
	echo '<!--';
}

function TEXT_JAVASCRIPT_END()
{
	echo '// -->';
	echo '</script>';
}

// Check the players login.  If a player has lost their ship in any way,
// this function will redirect them to the appropriate area,
// and will return 'false' to the calling script/function.  If the user somehow
// does not have a BNT account, the user will be directed to the player creation
// area.
function CheckLogin()
{
	global $smcFunc, $scripturl, $txt, $user_info, $context;
	global $dbtables, $newbie_nice, $server_closed;
	
	// Check to make sure the server is open before doing anything else.
	if ($server_closed)
	{
		echo '
					<p>', $txt['bnt_global_sclosed'], '</p>';
		return false;
	}
	
	// Make sure user has a BNT account
	$result = $smcFunc['db_query']('', '
		SELECT *
		FROM {raw:db_ships}
		WHERE user_id = {int:user_id}',
		array(
			'db_ships' => $dbtables['ships'],
			'user_id' => $user_info['id'],
		)
	);

	// If the user already has an account, run the player checks
	if ($smcFunc['db_num_rows']($result) == 1)
	{
		// Get the player information from the very first query
		$playerinfo = $smcFunc['db_fetch_assoc']($result);
		$smcFunc['db_free_result']($result);
		
		// Check the players IP againt the database for an IP ban
		$ban_result = $smcFunc['db_query']('', '
			SELECT *
			FROM {raw:db_bans}
			WHERE {string:ip} LIKE ban_mask',
			array(
				'db_bans' => $dbtables['ip_bans'],
				'ip' => $_SERVER['REMOTE_ADDR']
			)
		);
		
		// If there is a match, kill the login process.
		if (($smcFunc['db_num_rows']($ban_result)) != 0 )
		{
			echo '
						<p>', $txt['bnt_login_banned'], '<p>';
			return false;
		}
		$smcFunc['db_free_result']($ban_result);
		
		// Check if player's ship has not been destroyed
		if ($playerinfo['ship_destroyed'] == "N")
		{
			// Update last_login to keep players online indicator up to date.
			$update = $smcFunc['db_query']('', '
				UPDATE {raw:db_ships}
				SET last_login = NOW(),
					ip_address = {string:ip_address}
				WHERE ship_id = {int:ship_id}',
				array(
					'db_ships' => $dbtables['ships'],
					'ip_address' => $_SERVER['REMOTE_ADDR'],
					'ship_id' => $playerinfo['ship_id']
				)
			);
			return $playerinfo;
		}
		else
		{	
			// Player had a ship . . . it was destroyed, but the player had an escape pod.
			if ($playerinfo['dev_escapepod'] == "Y")
			{
				$update = $smcFunc['db_query']('', '
					UPDATE {raw:db_ships}
					SET hull = 0,
						engines = 0,
						power = 0,
						computer = 0,
						sensors = 0,
						beams = 0,
						torp_launchers = 0,
						torps = 0,
						armor = 0,
						armor_pts = 100,
						cloak = 0,
						shields = 0,
						sector = 0,
						ship_ore = 0,
						ship_organics = 0,
						ship_energy = 500,
						ship_colonists = 0,
						ship_goods = 0,
						ship_fighters = 100,
						on_planet = "N",
						dev_warpedit = 0,
						dev_genesis = 0,
						dev_beacon = 0,
						dev_emerwarp = 0,
						dev_escapepod = "N",
						dev_fuelscoop = "N",
						dev_minedeflector = 0,
						ship_destroyed = "N",
						dev_lssd = "N"
					WHERE ship_id = {int:ship_id}',
					array(
						'db_ships' => $dbtables['ships'],
						'ship_id' => $playerinfo['ship_id']
					)
				);
				
				$txt['bnt_login_died'] = str_replace("[scripturl]", $scripturl, $txt['bnt_login_died']);
				echo '
					<p>', $txt['bnt_login_died'], '</p>';
				TextMainMenu();
				return false;
			}
			// Player had a ship, it was destroyed but the player had no escape pod.
			else
			{
				$txt['bnt_login_dead'] = str_replace("[scripturl]", $scripturl, $txt['bnt_login_dead']);
				echo '
					<p>', $txt['bnt_login_dead'], '</p>';

				// Check if $newbie_nice is set, if so, verify ship limits
				if ($newbie_nice == "YES")
				{
					global $newbie_hull, $newbie_engines, $newbie_power, $newbie_computer;
					global $newbie_sensors, $newbie_armor, $newbie_shields, $newbie_beams;
					global $newbie_torp_launchers, $newbie_cloak;
				
					$result = $smcFunc['db_query']('', '
						SELECT hull, engines, power, computer, sensors, armor, shields, beams, torp_launchers, cloak
						FROM {raw:db_ships}
						WHERE ship_id = {int:ship_id}
						AND hull <= {int:newbie_hull} 
						AND engines <= {int:newbie_engines}
						AND power <= {int:newbie_power} 
						AND computer <= {int:newbie_computer} 
						AND sensors <= {int:newbie_sensors}
						AND armor <= {int:newbie_armor} 
						AND shields <= {int:newbie_shields} 
						AND beams <= {int:newbie_beams}
						AND torp_launchers <= {int:newbie_torp_launchers} 
						AND cloak <= {int:newbie_cloak}',
						array(
							'db_ships' => $dbtables['ships'],
							'ship_id' => $playerinfo['ship_id'],
							'newbie_hull' => $newbie_hull,
							'newbie_engines' => $newbie_engines,
							'newbie_power' => $newbie_power,
							'newbie_computer' => $newbie_computer,
							'newbie_sensors' => $newbie_sensors,
							'newbie_armor' => $newbie_armor,
							'newbie_shields' => $newbie_shields,
							'newbie_beams' => $newbie_beams,
							'newbie_torp_launchers' => $newbie_torp_launchers,
							'newbie_cloak' => $newbie_cloak
						)
					);
					
					if ($smcFunc['db_num_rows']($result) > 0)
					{
						// Player was still in newbie status, give them another chance
						
						$update = $smcFunc['db_query']('', '
							UPDATE {raw:db_ships}
							SET hull = 0,
								engines = 0,
								power = 0,
								computer = 0,
								sensors = 0,
								beams = 0,
								torp_launchers = 0,
								torps = 0,
								armor = 0,
								armor_pts = 100,
								cloak = 0,
								shields = 0,
								sector = 0,
								ship_ore = 0,
								ship_organics = 0,
								ship_energy = 500,
								ship_colonists = 0,
								ship_goods = 0,
								ship_fighters = 100,
								credits = 1000,
								on_planet = "N",
								dev_warpedit = 0,
								dev_genesis = 0,
								dev_beacon = 0,
								dev_emerwarp = 0,
								dev_escapepod = "N",
								dev_fuelscoop = "N",
								dev_minedeflector = 0,
								ship_destroyed = "N",
								dev_lssd = "N"
							WHERE ship_id = {int:ship_id}',
							array(
								'db_ships' => $dbtables['ships'],
								'ship_id' => $playerinfo['ship_id']
							)
						);
						echo '
					<p>', $txt['bnt_login_newbie'], '</p>';
						TextMainMenu();
						return false;
					}
					else
					{
						// Player starts over, treat as new player creation.
						$txt['bnt_login_newlife'] = str_replace("[scripturl]", $scripturl, $txt['bnt_login_newlife']);
						echo '
					<p>', $txt['bnt_login_loser'], '</p>
					<p>', $txt['bnt_login_newlife'], '</p>';
						return false;
					}
					$smcFunc['db_free_result']($result);
				}
				else
				{
					// Newbie nice is not set, player is dead and has to start over.
					$txt['bnt_login_newlife'] = str_replace("[scripturl]", $scripturl, $txt['bnt_login_newlife']);
					echo '
					<p>', $txt['bnt_login_loser'], '</p>
					<p>', $txt['bnt_login_newlife'], '</p>';
					return false;
				}
			}
		}
	}
	else
	{
		// This is a new player, display the character creation screen.
		$txt['bnt_global_nochar'] = str_replace("[scripturl]", $scripturl, $txt['bnt_global_nochar']);
		echo '
					<p>', $txt['bnt_global_nochar'], '</p>';
		return false;
	}
}

function playerlog($sid, $log_type, $data = "")
{
	global $smcFunc;
	global $dbtables;
	
	// Write log_entry to the player's log - identified by player's ship_id - sid.
	if ($sid != "" && !empty($log_type))
	{
		$smcFunc['db_insert']('insert',
			$dbtables['logs'],
			array(
				'ship_id' => 'int',
				'type' => 'int',
				'time' => 'string',
				'data' => 'string'
			),
			array(
				$sid,
				$log_type,
				Now(),
				$data
			),
			''
		);
	}
}

function adminlog($log_type, $data = "")
{
	global $smcFunc;
	global $dbtables;
	
	// Write log_entry to the admin log.
	if (!empty($log_type))
	{
		$smcFunc['db_insert']('insert',
			$dbtables['logs'],
			array(
				'ship_id' => 'int',
				'type' => 'int',
				'time' => 'string', 
				'data' => 'string'
			),
			array(
				0, $log_type, Now(), $data
			),
			''
		);
	}
}

function gen_score($sid)
{
	global $smcFunc;
	global $ore_price;
	global $organics_price;
	global $goods_price;
	global $energy_price;
	global $upgrade_cost;
	global $upgrade_factor;
	global $dev_genesis_price;
	global $dev_beacon_price;
	global $dev_emerwarp_price;
	global $dev_warpedit_price;
	global $dev_minedeflector_price;
	global $dev_escapepod_price;
	global $dev_fuelscoop_price;
	global $dev_lssd_price;
	global $fighter_price;
	global $torpedo_price;
	global $armor_price;
	global $colonist_price;
	global $base_ore;
	global $base_goods;
	global $base_organics;
	global $base_credits;
	global $dbtables;

	$calc_hull = 'ROUND(pow(' . $upgrade_factor . ',hull))';
	$calc_engines = 'ROUND(pow(' . $upgrade_factor . ',engines))';
	$calc_power = 'ROUND(pow(' . $upgrade_factor . ',power))';
	$calc_computer = 'ROUND(pow(' . $upgrade_factor . ',computer))';
	$calc_sensors = 'ROUND(pow(' . $upgrade_factor . ',sensors))';
	$calc_beams = 'ROUND(pow(' . $upgrade_factor . ',beams))';
	$calc_torp_launchers = 'ROUND(pow(' . $upgrade_factor . ',torp_launchers))';
	$calc_shields = 'ROUND(pow(' . $upgrade_factor . ',shields))';
	$calc_armor = 'ROUND(pow(' . $upgrade_factor . ',armor))';
	$calc_cloak = 'ROUND(pow(' . $upgrade_factor . ',cloak))';
	$calc_levels = '(' . $calc_hull . '+' . $calc_engines . '+' . $calc_power . '+' . $calc_computer . '+' . $calc_sensors . '+' . $calc_beams . '+' . $calc_torp_launchers . '+' . $calc_shields . '+' . $calc_armor . '+' . $calc_cloak . ')*' . $upgrade_cost;

	$calc_torps = $dbtables['ships'] . '.torps*' . $torpedo_price;
	$calc_armor_pts = 'armor_pts*' . $armor_price;
	$calc_ship_ore = 'ship_ore*' . $ore_price;
	$calc_ship_organics = 'ship_organics*' . $organics_price;
	$calc_ship_goods = 'ship_goods*' . $goods_price;
	$calc_ship_energy = 'ship_energy*' . $energy_price;
	$calc_ship_colonists = 'ship_colonists*' . $colonist_price;
	$calc_ship_fighters = 'ship_fighters*' . $fighter_price;
	$calc_equip = $calc_torps. '+' . $calc_armor_pts . '+' . $calc_ship_ore .'+' . $calc_ship_organics . '+' . $calc_ship_goods . '+' . $calc_ship_energy . '+' . $calc_ship_colonists . '+' . $calc_ship_fighters;

	$calc_dev_warpedit = 'dev_warpedit*' . $dev_warpedit_price;
	$calc_dev_genesis = 'dev_genesis*' . $dev_genesis_price;
	$calc_dev_beacon = 'dev_beacon*' . $dev_beacon_price;
	$calc_dev_emerwarp = 'dev_emerwarp*' . $dev_emerwarp_price;
	$calc_dev_escapepod = 'IF(dev_escapepod="Y", ' . $dev_escapepod_price . ', 0)';
	$calc_dev_fuelscoop = 'IF(dev_fuelscoop="Y", ' . $dev_fuelscoop_price . ', 0)';
	$calc_dev_lssd = 'IF(dev_lssd="Y", ' . $dev_lssd_price . ', 0)';
	$calc_dev_minedeflector = 'dev_minedeflector*' . $dev_minedeflector_price;
	$calc_dev = $calc_dev_warpedit . '+' . $calc_dev_genesis . '+' . $calc_dev_beacon . '+' . $calc_dev_emerwarp . '+' . $calc_dev_escapepod . '+' . $calc_dev_fuelscoop . '+' . $calc_dev_minedeflector . '+' . $calc_dev_lssd;

	$calc_planet_goods = 'if(' . $dbtables['planets'] . '.planet_id,SUM(' . $dbtables['planets'] . '.organics)*' . $organics_price . '+SUM(' . $dbtables['planets'] . '.ore)*' . $ore_price . '+SUM(' . $dbtables['planets'] . '.goods)*' . $goods_price . '+SUM(' . $dbtables['planets'] . '.energy)*' . $energy_price;
	$calc_planet_colonists = 'SUM(' . $dbtables['planets'] . '.colonists)*' . $colonist_price;
	$calc_planet_defence = 'SUM(' . $dbtables['planets'] . '.fighters)*' . $fighter_price . '+IF(' . $dbtables['planets'] . '.base="Y", ' . $base_credits . '+SUM(' . $dbtables['planets'] . '.torps)*' . $torpedo_price . ', 0)';
	$calc_planet_credits = 'SUM(' . $dbtables['planets'] . '.credits),0)';
	
	$result = $smcFunc['db_query']('', '
		SELECT ({raw:calc_levels}+{raw:calc_equip}+{raw:calc_dev}+{raw:db_ships}.credits+{raw:calc_planet_goods}+{raw:calc_planet_colonists}+{raw:calc_planet_defence}+{raw:calc_planet_credits}) AS score
		FROM {raw:db_ships}
			LEFT JOIN {raw:db_planets}
			ON {raw:db_planets}.owner = ship_id 
		WHERE ship_id = {int:sid}
		AND ship_destroyed = "N"',
		array(
			'db_ships' => $dbtables['ships'],
			'db_planets' => $dbtables['planets'],
			'calc_levels' => $calc_levels,
			'calc_equip' => $calc_equip,
			'calc_dev' => $calc_dev,
			'calc_planet_goods' => $calc_planet_goods,
			'calc_planet_colonists' => $calc_planet_colonists,
			'calc_planet_defence' => $calc_planet_defence,
			'calc_planet_credits' => $calc_planet_credits,
			'sid' => $sid
		)
	);
  
	$row = $smcFunc['db_fetch_assoc']($result);
	$score = $row['score'];
	$smcFunc['db_free_result']($result);
	
	$result = $smcFunc['db_query']('', '
		SELECT balance, loan
		FROM {raw:db_ibank_accounts}
		WHERE ship_id = {int:sid}
		LIMIT 1',
		array(
			'db_ibank_accounts' => $dbtables['ibank_accounts'],
			'sid' => $sid
		)
	);

	if ($smcFunc['db_num_rows']($result) > 0)
	{
		$row = $smcFunc['db_fetch_assoc']($result);
		$score += ($row['balance'] - $row['loan']);
		$smcFunc['db_free_result']($result);
	}
	$score = ROUND(SQRT($score));
	
	$update = $smcFunc['db_query']('', '
		UPDATE {raw:db_ships}
		SET score = {int:score}
		WHERE ship_id = {int:sid}',
		array(
			'db_ships' => $dbtables['ships'],
			'score' => $score,
			'sid' => $sid
		)
	);
	
	return $score;
}

function db_kill_player($ship_id, $newsskip = false)
{
	global $smcFunc, $txt;
	global $default_prod_ore;
	global $default_prod_organics;
	global $default_prod_goods;
	global $default_prod_energy;
	global $default_prod_fighters;
	global $default_prod_torp;
	global $dbtables;

	$update = $smcFunc['db_query']('', '
		UPDATE {raw:db_ships}
		SET user_id = NULL,
			ship_destroyed = "Y",
			on_planet = "N",
			sector = 0,
			cleared_defences = NULL
		WHERE ship_id = {int:ship_id}',
		array(
			'db_ships' => $dbtables['ships'],
			'ship_id' => $ship_id
		)
	);
	
	$delete = $smcFunc['db_query']('', '
		DELETE FROM {raw:db_bounty}
		WHERE placed_by = {int:ship_id}',
		array(
			'db_bounty' => $dbtables['bounty'],
			'ship_id' => $ship_id
		)
	);

	$result = $smcFunc['db_query']('', '
		SELECT DISTINCT sector_id
		FROM {raw:db_planets}
		WHERE owner = {int:ship_id}
		AND base = "Y"',
		array(
			'db_planets' => $dbtables['planets'],
			'ship_id' => $ship_id
		)
	);

	$i = 0;
	
	while ($sectors[$i] = $smcFunc['db_fetch_assoc']($result))
	{
		$i++;
	}
	$smcFunc['db_free_result']($result);
	
	$update = $smcFunc['db_query']('', '
		UPDATE {raw:db_planets}
		SET owner = 0,
			fighters = 0,
			base = "N"
		WHERE owner = {int:ship_id}',
		array(
			'db_planets' => $dbtables['planets'],
			'ship_id' => $ship_id
		)
	);
	
	if ($i > 0)
	{
		foreach ($sectors as $sector)
		{
			echo '<br>checking sector ownership: ', $sector['sector_id'], '</br>';
			if ($sector['sector_id'] > 0)
				calc_ownership($sector['sector_id']);
		}
	}
	
	$result = $smcFunc['db_query']('', '
		SELECT ship_id
		FROM {raw:db_sector_defence}
		WHERE ship_id = {int:ship_id}',
		array(
			'db_sector_defence' => $dbtables['sector_defence'],
			'ship_id' => $ship_id
		)
	);
	
	if ($smcFunc['db_num_rows']($result) > 0)
	{	
		echo 'deleting sector defences for ship id: ', $ship_id;
		$delete = $smcFunc['db_query']('', '
			DELETE FROM {raw:db_sector_defence}
			WHERE ship_id = {int:ship_id}',
			array(
				'db_sector_defence' => $dbtables['sector_defence'],
				'ship_id' => $ship_id
			)
		);
	}
	$smcFunc['db_free_result']($result);
	
	$result = $smcFunc['db_query']('', '
		SELECT zone_id
		FROM {raw:db_zones}
		WHERE corp_zone="N"
		AND owner = {int:ship_id}',
		array(
			'db_zones' => $dbtables['zones'],
			'ship_id' => $ship_id
		)
	);

	if ($smcFunc['db_num_rows']($result) <> 0)
	{
		$zone = $smcFunc['db_fetch_assoc']($result);
		$smcFunc['db_free_result']($result);
		
		$update = $smcFunc['db_query']('', '
			UPDATE {raw:db_universe}
			SET zone_id = 1
			WHERE zone_id = {int:zone_id}',
			array(
				'db_universe' => $dbtables['universe'],
				'zone_id' => $zone['zone_id']
			)
		);
	}

	$result = $smcFunc['db_query']('', '
		SELECT character_name
		FROM {raw:db_ships}
		WHERE ship_id = {int:ship_id}',
		array(
			'db_ships' => $dbtables['ships'],
			'ship_id' => $ship_id
		)
	);
	$name = $smcFunc['db_fetch_assoc']($result);
	$smcFunc['db_free_result']($result);
	
	if ($newsskip == false)
	{
		$headline = $name['character_name'] . $txt['bnt_killheadline'];
		$newstext = str_replace("[name]", $name['character_name'], $txt['bnt_news_killed']);

		$smcFunc['db_insert']('insert',
			$dbtables['news'],
			array(
				'headline' => 'string',
				'newstext' => 'string',
				'user_id' => 'int',
				'date' => 'string',
				'news_type' => 'string'
			),
			array(
				$headline,
				$newstext,
				$ship_id,
				Now(),
				'killed'
			),
			''
		);
	}
}

function Number($number, $decimals = 0)
{
	
	return number_format($number, $decimals);
}

function NUM_HOLDS($level_hull)
{
	global $level_factor;
	return round(mypw($level_factor, $level_hull) * 100);
}

function NUM_ENERGY($level_power)
{
	global $level_factor;
	return round(mypw($level_factor, $level_power) * 500);
}

function NUM_FIGHTERS($level_computer)
{
	global $level_factor;
	return round(mypw($level_factor, $level_computer) * 100);
}

function NUM_TORPEDOES($level_torp_launchers)
{
	global $level_factor;
	return round(mypw($level_factor, $level_torp_launchers) * 100);
}

function NUM_ARMOUR($level_armor)
{
	global $level_factor;
	return round(mypw($level_factor, $level_armor) * 100);
}

function NUM_BEAMS($level_beams)
{
	global $level_factor;
	return round(mypw($level_factor, $level_beams) * 100);
}

function NUM_SHIELDS($level_shields)
{
	global $level_factor;
	return round(mypw($level_factor, $level_shields) * 100);
}

function SCAN_SUCCESS($level_scan, $level_cloak)
{
	return (5 + $level_scan - $level_cloak) * 5;
}

function SCAN_ERROR($level_scan, $level_cloak)
{
	global $scan_error_factor;

	$sc_error = (4 + $level_scan / 2 - $level_cloak / 2) * $scan_error_factor;

	if ($sc_error < 1)
		$sc_error = 1;

	if ($sc_error > 99)
		$sc_error = 99;

	return $sc_error;
}

function energy_scooped($playerinfo, $distance, $triptime, $free_power)
{
	/*	If the player has a fuel scoop, energy scooped is distance traveled multiplied by 100.
		Otherwise set energy scooped to 0. */
	if ($playerinfo['dev_fuelscoop'] == "Y")
		$energyscooped = $distance * 100;
	else
		$energyscooped = 0;
	
	// Minimum energy scooped is always 100.
	if ($playerinfo['dev_fuelscoop'] == "Y" && $energyscooped == 0 && $triptime == 1)
		$energyscooped = 100;
	
	// If the player gathered more energy than he can hold, just gather the max the player can hold.
	if ($free_power < $energyscooped)
		$energyscooped = $free_power;
	
	// Check for number less than 1.
	if ($energyscooped < 1)
		$energyscooped = 0;
	
	return $energyscooped;
}

function explode_mines($sector, $num_mines)
{
	global $smcFunc;
	global $dbtables;
	
	$result = $smcFunc['db_query']('', '
		SELECT *
		FROM {raw:db_sector_defence}
		WHERE sector_id = {int:sector}
		AND defence_type = "M"
		ORDER BY quantity ASC',
		array(
			'db_sector_defence' => $dbtables['sector_defence'],
			'sector' => $sector
		)
	);
   
	//Put the defence information into the array "defenceinfo"
    if ($smcFunc['db_num_rows']($result) > 0)
    {
		while (($row = $smcFunc['db_fetch_assoc']($result)) && ($num_mines > 0))
		{
			if ($row['quantity'] > $num_mines)
			{
				$update = $smcFunc['db_query']('', '
					UPDATE {raw:db_sector_defence}
					SET quantity = quantity - {int:num_mines}
					WHERE defence_id = {int:defence_id}',
					array(
						'db_sector_defence' => $dbtables['sector_defence'],
						'num_mines' => $num_mines,
						'defence_id' => $row['defence_id']
					)
				);
				$num_mines = 0;
			}
			else
			{
				$delete = $smcFunc['db_query']('', '
					DELETE FROM {raw:db_sector_defence}
					WHERE defence_id = {int:defence_id}',
					array(
						'db_sector_defence' => $dbtables['sector_defence'],
						'defence_id' => $row['defence_id']
					)
				);
				$num_mines -= $row['quantity'];
			}
		}
    }
}

function destroy_fighters($sector, $num_fighters)
{
    global $smcFunc;
	global $dbtables;
	
	$result = $smcFunc['db_query']('', '
		SELECT *
		FROM {raw:db_sector_defence}
		WHERE sector_id = {int:sector_id}
		AND defence_type = "F"
		ORDER BY quantity ASC',
		array(
			'db_sector_defence' => $dbtables['sector_defence'],
			'sector_id' => $sector
		)
	);
	
    //Put the defence information into the array "defenceinfo"
	if ($smcFunc['db_num_rows']($result) > 0)
    {
		while ($row = $smcFunc['db_fetch_assoc']($result))
		{
			if($row['quantity'] > $num_fighters)
			{
				$update = $smcFunc['db_query']('', '
					UPDATE {raw:db_sector_defence}
					SET quantity = quantity - {int:num_fighters}
					WHERE defence_id = {int:defence_id}',
					array(
						'db_sector_defence' => $dbtables['sector_defence'],
						'num_fighters' => $num_fighters,
						'defence_id' => $row['defence_id']
					)
				);
				$num_fighters = 0;
			}
			else
			{
				$delete = $smcFunc['db_query']('', '
					DELETE FROM {raw:db_sector_defence}
					WHERE defence_id = {int:defence_id}',
					array(
						'db_sector_defence' => $dbtables['sector_defence'],
						'defence_id' => $row['defence_id']
					)
				);
				$num_fighters -= $row['quantity'];
			}
		}
    }
	$smcFunc['db_free_result']($result);
}

function message_defence_owner($sector, $message)
{
    global $smcFunc;
	global $dbtables;
	
	$result = $smcFunc['db_query']('', '
		SELECT *
		FROM {raw:db_sector_defence}
		WHERE sector_id = {int:sector_id}',
		array(
			'db_sector_defence' => $dbtables['sector_defence'],
			'sector_id' => $sector
		)
	);
	
    //Put the defence information into the array "defenceinfo"
	if ($smcFunc['db_num_rows']($result) > 0)
    {
		while ($row = $smcFunc['db_fetch_assoc']($result))
		{
			playerlog($row['ship_id'], LOG_RAW, $message);
		}
    }
	$smcFunc['db_free_result']($result);
}

function distribute_toll($sector, $toll, $total_fighters)
{
    global $smcFunc;
	global $dbtables;
	
	$result = $smcFunc['db_query']('', '
		SELECT *
		FROM {raw:db_sector_defence}
		WHERE sector_id = {int:sector_id}
		AND defence_type = "F"',
		array(
			'db_sector_defence' => $dbtables['sector_defence'],
			'sector_id' => $sector
		)
	);

    // Put the defence information into the array "defenceinfo"
    if ($smcFunc['db_num_rows']($result) > 0)
    {
		while ($row = $smcFunc['db_fetch_assoc']($result))
		{
			$toll_amount = round(($row['quantity'] / $total_fighters) * $toll);
			$update = $smcFunc['db_query']('', '
				UPDATE {raw:db_ships}
				SET credits = credits + {int:toll_amount}
				WHERE ship_id = {raw:ship_id}',
				array(
					'db_ships' => $dbtables['ships'],
					'toll_amount' => $toll_amount,
					'ship_id' => $row['ship_id']
				)
			);
			playerlog($row['ship_id'], LOG_TOLL_RECV, "$toll_amount|$sector");
		}
    }
	$smcFunc['db_free_result']($result);
}

function defence_vs_defence($ship_id)
{
	global $smcFunc, $txt;
	global $dbtables;
	
	$result = $smcFunc['db_query']('', '
		SELECT *
		FROM {raw:db_sector_defence}
		WHERE ship_id = {int:ship_id}',
		array(
			'db_sector_defence' => $dbtables['sector_defence'],
			'ship_id' => $ship_id
		)
	);
	
	if ($smcFunc['db_num_rows']($result) > 0)
	{
		while($row = $smcFunc['db_fetch_assoc']($result))
		{
			$deftype = $row['defence_type'] == 'F' ? 'Fighters' : 'Mines';
			$qty = $row['quantity'];
			
			$result2 = $smcFunc['db_query']('', '
				SELECT *
				FROM {raw:db_sector_defence}
				WHERE sector_id = {int:sector_id}
				AND ship_id <> {int:ship_id}
				ORDER BY quantity DESC',
				array(
					'db_sector_defence' => $dbtables['sector_defence'],
					'sector_id' => $row['sector_id'],
					'ship_id' => $ship_id
				)
			);
			
			if ($smcFunc['db_num_rows']($result2) > 0)
			{
				while($cur = $smcFunc['db_fetch_assoc']($result) && $qty > 0)
				{
					$targetdeftype = $cur['defence_type'] == 'F' ? $txt['bnt_fighters'] : $txt['bnt_mines'];
					
					if ($qty > $cur['quantity'])
					{
						$delete = $smcFunc['db_query']('', '
							DELETE FROM {raw:db_sector_defence}
							WHERE defence_id = {int:defence_id}',
							array(
								'db_sector_defence' => $dbtables['sector_defence'],
								'defence_id' => $cur['defence_id']
							)
						);
						
						$qty -= $cur['quantity'];
						
						$update = $smcFunc['db_query']('', '
							UPDATE {raw:db_sector_defence}
							SET quantity = {int:qty}
							WHERE defence_id = {int:defence_id}',
							array(
								'db_sector_defence' => $dbtables['sector_defence'],
								'qty' => $qty,
								'defence_id' => $row['defence_id']
							)
						);
						
						playerlog($cur['ship_id'], LOG_DEFS_DESTROYED, "$cur[quantity]|$targetdeftype|$row[sector_id]");
						playerlog($row['ship_id'], LOG_DEFS_DESTROYED, "$cur[quantity]|$deftype|$row[sector_id]");
					}
					else
					{
						$delete = $smcFunc['db_query']('', '
							DELETE FROM {raw:db_sector_defence}
							WHERE defence_id = {int:defence_id}',
							array(
								'db_sector_defence' => $dbtables['sector_defence'],
								'defence_id' => $row['defence_id']
							)
						);
						
						$update = $smcFunc['db_query']('', '
							UPDATE {raw:db_sector_defence}
							SET quantity = quantity - {int:qty}
							WHERE defence_id = {int:defence_id}',
							array(
								'db_sector_defence' => $dbtables['sector_defence'],
								'qty' => $qty,
								'defence_id' => $cur['defence_id']
							)
						);
						
						playerlog($cur['ship_id'], LOG_DEFS_DESTROYED, "$qty|$targetdeftype|$row[sector_id]");
						playerlog($row['ship_id'], LOG_DEFS_DESTROYED, "$qty|$deftype|$row[sector_id]");
						
						$qty = 0;
					}
				}
				$smcFunc['db_free_result']($result2);
			}
		}
		$smcFunc['db_free_result']($result);
		
		$delete = $smcFunc['db_query']('', '
			DELETE FROM {raw:db_sector_defence}
			WHERE quantity <= 0',
			array(
				'db_sector_defence' => $dbtables['sector_defence']
			)
		);
	}
}

function kick_off_planet($ship_id,$whichteam)
{
	global $smcFunc;
	global $dbtables;
	
	$result = $smcFunc['db_query']('', '
		SELECT *
		FROM {raw:db_planets}
		WHERE owner = {int:ship_id}',
		array(
			'db_planets' => $dbtables['planets'],
			'ship_id' => $ship_id
		)
	);
	
	if ($smcFunc['db_num_rows']($result) > 0)
	{
		while ($row = $smcFunc['db_fetch_assoc']($result))
		{
			$result2 = $smcFunc['db_query']('', '
				SELECT *
				FROM {raw:db_ships}
				WHERE on_planet = "Y"
				AND planet_id = {int:planet_id}
				AND ship_id <> {int:ship_id}',
				array(
					'db_ships' => $dbtables['ships'],
					'planet_id' => $row['planet_id'],
					'ship_id' => $ship_id
				)
			);
			
			if ($smcFunc['db_num_rows']($result2) > 0)
			{
				while($cur = $smcFunc['db_fetch_assoc']($result))
				{
					$update = $smcFunc['db_query']('', '
						UPDATE {raw:db_ships}
						SET on_planet = "N",
							planet_id = 0
						WHERE ship_id = {int:ship_id}',
						array(
							'db_ships' => $dbtables['ships'],
							'ship_id' => $cur['ship_id']
						)
					);
					playerlog($cur['ship_id'], LOG_PLANET_EJECT, "$cur[sector]|$row[character_name]");
				}
				$smcFunc['db_free_result']($result2);
			}
		}
		$smcFunc['db_free_result']($result);
	}
}

function calc_ownership($sector)
{
	global $smcFunc, $txt;
	global $min_bases_to_own, $dbtables;

	$result = $smcFunc['db_query']('', '
		SELECT owner, corp
		FROM {raw:db_planets}
		WHERE sector_id = {int:sector}
		AND base = "Y"',
		array(
			'db_planets' => $dbtables['planets'],
			'sector' => $sector
		)
	);
	$num_bases = $smcFunc['db_num_rows']($result);

	$i = 0;
	if ($num_bases > 0)
	{
		while ($row = $smcFunc['db_fetch_assoc']($result))
		{
			$bases[$i] = $row;
			$i++;
		}
	}
	else
		return $txt['bnt_global_sector'];

	$owner_num = 0;

	foreach ($bases as $curbase)
	{
		$curcorp=-1;
		$curship=-1;
		$loop = 0;
		
		while ($loop < $owner_num)
		{
			if ($curbase['corp'] != 0)
			{
				if ($owners[$loop]['type'] == 'C')
				{
					if ($owners[$loop]['id'] == $curbase['corp'])
					{
						$curcorp = $loop;
						$owners[$loop]['num']++;
					}
				}
			}

			if ($owners[$loop]['type'] == 'S')
			{
				if ($owners[$loop]['id'] == $curbase['owner'])
				{
					$curship = $loop;
					$owners[$loop]['num']++;
				}
			}
			$loop++;
		}

		if($curcorp == -1)
		{
			if($curbase['corp'] != 0)
			{
				$curcorp = $owner_num;
				$owner_num++;
				$owners[$curcorp]['type'] = 'C';
				$owners[$curcorp]['num'] = 1;
				$owners[$curcorp]['id'] = $curbase['corp'];
			}
		}

		if($curship == -1)
		{
			if($curbase['owner'] != 0)
			{
				$curship = $owner_num;
				$owner_num++;
				$owners[$curship]['type'] = 'S';
				$owners[$curship]['num'] = 1;
				$owners[$curship]['id'] = $curbase['owner'];
			}
		}
	}
	$smcFunc['db_free_result']($result);
	
	// We've got all the contenders with their bases.
	// Time to test for conflict
	$loop = 0;
	$nbcorps = 0;
	$nbships = 0;
	while($loop < $owner_num)
	{
		if($owners[$loop]['type'] == 'C')
			$nbcorps++;
		else
		{
			$result = $smcFunc['db_query']('', '
				SELECT team
				FROM {raw:db_ships}
				WHERE ship_id = {int:ship_id}',
				array(
					'db_ships' => $dbtables['ships'],
					'ship_id' => $owners[$loop]['id']
				)
			);
			if ($result && $smcFunc['db_num_rows']($result) != 0)
			{
				$curship = $smcFunc['db_fetch_assoc']($result);
				$ships[$nbships] = $owners[$loop]['id'];
				$scorps[$nbships] = $curship['team'];
				$nbships++;
			}
			$smcFunc['db_free_result']($result);
		}
		$loop++;
	}

	//More than one corp, WAR
	if ($nbcorps > 1)
	{
		$update= $smcFunc['db_query']('', '
			UPDATE {raw:db_universe}
			SET zone_id = 4
			WHERE sector_id = {int:sector}',
			array(
				'db_universe' => $dbtables['universe'],
				'sector' => $sector
			)
		);
		return $txt['bnt_global_warzone'];
	}

	//More than one unallied ship, WAR
	$numunallied = 0;
	foreach ($scorps as $corp)
	{
		if ($corp == 0)
			$numunallied++;
	}
	
	if ($numunallied > 1)
	{
		$update= $smcFunc['db_query']('', '
			UPDATE {raw:db_universe}
			SET zone_id = 4
			WHERE sector_id = {int:sector}',
			array(
				'db_universe' => $dbtables['universe'],
				'sector' => $sector
			)
		);
		return $txt['bnt_global_warzone'];
	}

	//Unallied ship, another corp present, WAR
	if($numunallied > 0 && $nbcorps > 0)
	{
		$update= $smcFunc['db_query']('', '
			UPDATE {raw:db_universe}
			SET zone_id = 4
			WHERE sector_id = {int:sector}',
			array(
				'db_universe' => $dbtables['universe'],
				'sector' => $sector
			)
		);
		return $txt['bnt_global_warzone'];
	}

	//Unallied ship, another ship in a corp, WAR
	if ($numunallied > 0)
	{
		$query = 'SELECT team FROM {raw:db_ships} WHERE (';
		$i = 0;
		foreach($ships as $ship)
		{
			$query = $query . 'ship_id = ' . $ship;
			$i++;
			if ($i != $nbships)
				$query = $query . ' OR ';
			else
				$query = $query . ')';
		}
		$query = $query .' AND team != 0';
		
		$result= $smcFunc['db_query']('', 
			$query,
			array(
				'db_ships' => $dbtables['ships']
			)
		);
		
		if($smcFunc['db_num_rows']($result) != 0)
		{
			$update = $smcFunc['db_query']('', '
				UPDATE {raw:db_universe}
				SET zone_id = 4
				WHERE sector_id = {int:sector}',
				array(
					'db_universe' => $dbtables['universe'],
					'sector' => $sector
				)
			);
			return $txt['bnt_global_warzone'];
		}
		$smcFunc['db_free_result']($result);
	}

	//Ok, all bases are allied at this point. Let's make a winner.
	$winner = 0;
	$i = 1;
	while ($i < $owner_num)
	{
		if ($owners[$i]['num'] > $owners[$winner]['num'])
			$winner = $i;
		elseif ($owners[$i]['num'] == $owners[$winner]['num'])
		{
			if ($owners[$i]['type'] == 'C')
				$winner = $i;
		}
		$i++;
	}

	if ($owners[$winner]['num'] < $min_bases_to_own)
	{
		$update = $smcFunc['db_query']('', '
			UPDATE {raw:db_universe}
			SET zone_id = 1
			WHERE sector_id = {int:sector}',
			array(
				'db_universe' => $dbtables['universe'],
				'sector' => $sector
			)
		);
		return $txt['bnt_global_nzone'];
	}


	if ($owners[$winner]['type'] == 'C')
	{
		$result = $smcFunc['db_query']('', '
			SELECT zone_id
			FROM {raw:db_zones}
			WHERE corp_zone = "Y" && owner = {int:id}',
			array(
				'db_zones' => $dbtables['zones'],
				'id' => $owners[$winner]['id']
			)
		);
		
		$zone = $smcFunc['db_fetch_assoc']($result);
		$smcFunc['db_free_result']($result);

		$result = $smcFunc['db_query']('', '
			SELECT team_name
			FROM {raw:db_teams}
			WHERE id = {int:id}',
			array(
				'db_teams' => $dbtables['teams'],
				'id' => $owners[$winner]['id']
			)
		);
		$corp = $smcFunc['db_fetch_assoc']($result);
		$smcFunc['db_free_result']($result);

		$update = $smcFunc['db_query']('', '
			UPDATE {raw:db_universe}
			SET zone_id = {int:zone_id}
			WHERE sector_id = {int:sector}',
			array(
				'db_universe' => $dbtables['universe'],
				'zone_id' => $zone['zone_id'],
				'sector' => $sector
			)
		);
		return "$txt[bnt_global_team] $corp[team_name]!";
	}
	else
	{
		$onpar = 0;
		foreach ($owners as $curowner)
		{
			if ($curowner['type'] == 'S' && $curowner['id'] != $owners[$winner]['id'] && $curowner['num'] == $owners['winners']['num'])
			{
				$onpar = 1;
				break;
			}
		}

		//Two allies have the same number of bases
		if ($onpar == 1)
		{
			$update = $smcFunc['db_query']('', '
				UPDATE {raw:db_universe}
				SET zone_id = 1
				WHERE sector_id = {int:sector}',
				array(
					'db_universe' => $dbtables['universe'],
					'sector' => $sector
				)
			);
			return $txt['bnt_global_nzone'];
		}
		else
		{
			$result = $smcFunc['db_query']('', '
				SELECT zone_id
				FROM {raw:db_zones}
				WHERE corp_zone = "N"
				AND owner = {int:id}',
				array(
					'db_zones' => $dbtables['zones'],
					'id' => $owners[$winner]['id']
				)
			);
			$zone = $smcFunc['db_fetch_assoc']($result);
			$smcFunc['db_free_result']($result);

			$result = $smcFunc['db_query']('', '
				SELECT character_name
				FROM {raw:db_ships}
				WHERE ship_id = {int:id}',
				array(
					'db_ships' => $dbtables['ships'],
					'id' => $owners[$winner]['id']
				)
			);
			$ship = $smcFunc['db_fetch_assoc']($result);
			$smcFunc['db_free_result']($result);

			$update = $smcFunc['db_query']('', '
				UPDATE {raw:db_universe}
				SET zone_id = {int:zone_id}
				WHERE sector_id = {int:sector}',
				array(
					'db_universe' => $dbtables['universe'],
					'zone_id' => $zone['zone_id'],
					'sector' => $sector
				)
			);
			return "$txt[bnt_global_player] $ship[character_name]!";
		}
	}
}

function player_insignia_name($user_id)
{

	global $smcFunc, $txt, $user_info;
	global $dbtables;

	$result = $smcFunc['db_query']('', '
		SELECT score
		FROM {raw:db_ships}
		WHERE user_id = {int:user_id}',
		array(
			'db_ships' => $dbtables['ships'], 
			'user_id' => $user_id,
		)
	);
	$playerinfo = $smcFunc['db_fetch_assoc']($result);

	$score_array = array('1000', '3000', '6000', '9000', '12000', '15000', '20000', '40000', '60000', '80000', '100000', '120000', '160000', '200000', '250000', '300000', '350000', '400000', '450000', '500000');

	for ($i = 0; $i < count($score_array); $i++)
	{
	    if ($playerinfo['score'] < $score_array[$i])
		{
			$player_insignia = $txt['bnt_insignia'][$i];
			break;
		}
	}
	
	if (!isset($player_insignia))
		$player_insignia = end($txt['bnt_insignia']);
		
	$smcFunc['db_free_result']($result);

	return $player_insignia;
}

function t_port($ptype)
{

	global $txt;

	switch ($ptype)
	{
	    case "ore":
	        $ret = $txt['bnt_ore'];
	        break;
	    case "none":
	        $ret = $txt['bnt_none'];
	        break;
	    case "energy":
	        $ret = $txt['bnt_energy'];
	        break;
	    case "organics":
	        $ret = $txt['bnt_organics'];
	        break;
	    case "goods":
	        $ret = $txt['bnt_goods'];
	        break;
	    case "special":
	        $ret = $txt['bnt_special'];
	        break;
	}

	return $ret;
}

function t_port_icon($ptype)
{

	global $txt, $settings;

	switch ($ptype)
	{
		case "credits":
	        $ret = '<img class="cargo_icon" alt="Cr" src="' .  $settings['images_url'] .  '/bnt/credits.gif">';
	        break;
		case "Colonists":
	        $ret = '<img class="cargo_icon" alt="Co" src="' .  $settings['images_url'] .  '/bnt/colonists.gif">';
	        break;
		case "energy":
	        $ret = '<img class="cargo_icon" alt="E" src="' .  $settings['images_url'] .  '/bnt/energy.gif">';
	        break;
		case "Fighters":
	        $ret = '<img class="cargo_icon" alt="F" src="' .  $settings['images_url'] .  '/bnt/fighter.gif">';
	        break;
	    case "goods":
	        $ret = '<img class="cargo_icon" alt="G" src="' .  $settings['images_url'] .  '/bnt/goods.gif">';
	        break;
	    case "ore":
	        $ret = '<img class="cargo_icon" alt="Ore" src="' . $settings['images_url'] .  '/bnt/ore.gif">';
	        break;
	    case "organics":
	        $ret = '<img class="cargo_icon" alt="Org" src="' .  $settings['images_url'] .  '/bnt/organics.gif">';
	        break;
	    case "planet":
	        $ret = '<img class="cargo_icon" alt="Pl" src="">';
	        break;
	    case "port":
	        $ret = '<img class="cargo_icon" alt="Po" src="">';
	        break;
	    case "special":
	        $ret = '<img class="cargo_icon" alt="S" src="' .  $settings['images_url'] .  '/bnt/special.gif">';
	        break;
	    case "Torpedoes":
	        $ret = '<img class="cargo_icon" alt="T" src="' .  $settings['images_url'] .  '/bnt/torpedo.gif">';
	        break;
	    case "base":
	        $ret = '<img class="cargo_icon" alt="Yes" src="' .  $settings['images_url'] .  '/bnt/base.gif">';
	        break;
	    case "base_none":
	        $ret = '<img class="cargo_icon" alt="No" src="' .  $settings['images_url'] .  '/bnt/base_none.gif">';
	        break;
	    case "sells":
	        $ret = '<img class="cargo_icon" alt="Yes" src="' .  $settings['images_url'] .  '/bnt/sells.gif">';
	        break;
	    case "sells_none":
	        $ret = '<img class="cargo_icon" alt="No" src="' .  $settings['images_url'] .  '/bnt/sells_none.gif">';
	        break;				
		default:
			$ret = '';
	}

	return $ret;
}

function stripnum($str)
{
    $output = preg_replace('/[^0-9]/','',$str);
    return $output;
}

function collect_bounty($attacker,$bounty_on)
{
	global $smcFunc, $txt;
	global $dbtables;

	$result = $smcFunc['db_query']('', '
		SELECT *
		FROM {raw:db_ships}, {raw:db_bounty}
		WHERE bounty_on = {int:bounty_on}
		AND bounty_on = ship_id
		AND placed_by <> 0',
		array(
			'db_ships' => $dbtables['ships'],
			'db_bounty' => $dbtables['bounty'],
			'bounty_on' => $bounty_on
		)
	);
	
    if ($smcFunc['db_num_rows']($result) > 0)
	{
		while ($bountydetails = $smcFunc['db_fetch_assoc']($result))
		{
			$placed_result = $smcFunc['db_query']('', '
				SELECT *
				FROM {raw:db_ships}
				WHERE ship_id = {int:placed_by}',
				array(
					'db_ships' => $dbtables['ships'],
					'placed_by' => $bountydetails['placed_by']
				)
			);
			
			$placed = $smcFunc['db_fetch_assoc']($placed_result);
			$smcFunc['db_free_result']($placed_result);
			
			$update = $smcFunc['db_query']('', '
				UPDATE {raw:db_ships}
				SET credits = credits + {int:amount}
				WHERE ship_id = {int:attacker}',
				array(
					'db_ships' => $dbtables['ships'],
					'amount' => $bountydetails['amount'],
					'attacker' => $attacker
				)
			);
			
			$delete = $smcFunc['db_query']('', '
				DELETE FROM {raw:db_bounty}
				WHERE bounty_id = {int:bounty_id}',
				array(
					'db_bounty' => $dbtables['bounty'],
					'bounty_id' => $bountydetails['bounty_id']
				)
			);
			
			playerlog($attacker, LOG_BOUNTY_CLAIMED, "$bountydetails[amount]|$bountydetails[character_name]|$placed");
			playerlog($bountydetails['placed_by'],LOG_BOUNTY_PAID,"$bountydetails[amount]|$bountydetails[character_name]");
		}
	}
	$smcFunc['db_free_result']($result);
	
	$delete = $smcFunc['db_query']('', '
		DELETE FROM {raw:db_bounty}
		WHERE bounty_on = {int:bounty_on}',
		array(
			'db_bounty' => $dbtables['bounty'],
			'bounty_on' => $bounty_on
		)
	);
}

function cancel_bounty($bounty_on)
{
	global $smcFunc;
	global $dbtables;
	
	$result = $smcFunc['db_query']('', '
		SELECT *
		FROM {raw:db_bounty}, {raw:db_ships}
		WHERE bounty_on = {int:bounty_on}
		AND bounty_on = ship_id',
		array(
			'db_bounty' => $dbtables['bounty'],
			'db_ships' => $dbtables['ships'],
			'bounty_on' => $bounty_on
		)
	);
   
	if ($smcFunc['db_num_rows']($result) > 0)
	{
		while ($row = $smcFunc['db_fetch_assoc']($result))
		{
			$bountydetails = $row;
			
			if($bountydetails['placed_by'] <> 0)
			{
				$update = $smcFunc['db_query']('', '
					UPDATE {raw:db_ships}
					SET credits = credits + {int:amount}
					WHERE ship_id = {int:placed_by}',
					array(
						'db_ships' => $dbtables['ships'],
						'amount' => $bountydetails['amount'],
						'placed_by' => $bountydetails['placed_by']
					)
				);
				
				playerlog($bountydetails['placed_by'], LOG_BOUNTY_CANCELLED, "$bountydetails[amount]|$bountydetails[character_name]");
			}
			
			$delete = $smcFunc['db_query']('', '
				DELETE FROM {raw:db_ships}
				WHERE bounty_id = {int:bounty_id}',
				array(
					'db_ships' => $dbtables['ships'],
					'bounty_id' => $dbtables['ships']
				)
			);
		}
	}
	$smcFunc['db_free_result']($result);
}

function get_player($ship_id)
{
	global $smcFunc, $txt;
	global $dbtables;
	
	$get_player_result = $smcFunc['db_query']('', '
		SELECT character_name
		FROM {raw:db_ships}
		WHERE ship_id = {int:ship_id}
		LIMIT 1',
		array(
			'db_ships' => $dbtables['ships'],
			'ship_id' => $ship_id
		)
	);
	if ($smcFunc['db_num_rows']($get_player_result) > 0)
	{
		$get_player_row = $smcFunc['db_fetch_assoc']($get_player_result);
		$character_name = $get_player_row['character_name'];
		$smcFunc['db_free_result']($get_player_result);
		return $character_name;
	}
	else
	{
		$smcFunc['db_free_result']($get_player_result);
		return $txt['bnt_unknown'];
	}
}

function log_move($ship_id,$sector_id)
{
   global $smcFunc;
   global $dbtables;
   
	$smcFunc['db_insert']('insert',
		$dbtables['movement_log'],
		array(
			'ship_id' => 'int',
			'sector_id' => 'int',
			'time' => 'string'
		),
		array(
			$ship_id,
			$sector_id,
			Now()
		),
		''
	);
}

function isLoanPending($ship_id)
{
	global $smcFunc;
	global $dbtables;
	global $IGB_lrate;
	
	$result = $smcFunc['db_query']('', '
		SELECT loan, UNIX_TIMESTAMP(loantime) AS time
		FROM {raw:db_ibank_accounts}
		WHERE ship_id = {int:ship_id}',
		array(
			'db_ibank_accounts' => $dbtables['ibank_accounts'],
			'ship_id' => $ship_id
		)
	);
	
	if ($smcFunc['db_num_rows']($result) > 0)
	{
		$account = $smcFunc['db_fetch_assoc']($result);
		$smcFunc['db_free_result']($result);

		if ($account['loan'] == 0)
			return false;

		$curtime = time();
		$difftime = ($curtime - $account['time']) / 60;
		
		if ($difftime > $IGB_lrate)
			return true;
		else
			return false;
	}
	else
		return false;
}

function get_player_name($userid)
{
	global $smcFunc;
	global $dbtables;

	$result = $smcFunc['db_query']('', '
		SELECT character_name
		FROM {raw:db_ships}
		WHERE ship_id = {int:userid}',
		array(
			'db_ships' => $dbtables['ships'],
			'userid' => $userid
		)
	);
	
	$name = $smcFunc['db_fetch_assoc']($result);
	$smcFunc['db_free_result']($result);
	
	return $name['character_name'];
}

function Now()
{
	$dt = date('Y-m-d H:i:s');
	return $dt;
}

// Assumes $day is a valid formatted time
function getpreviousday($day)
{
    //convert the formatted date into a timestamp
    $day = strtotime($day);

    //subtract one day in seconds from the timestamp
    $day = $day - 86400;

    //return the final amount formatted as YYYY/MM/DD
    return date("Y/m/d",$day);
}

// Assumes $day is a valid formatted time
function getnextday($day)
{
    //convert the formatted date into a timestamp
    $day = strtotime($day);

    //add one day in seconds to the timestamp
    $day = $day + 86400;

    //return the final amount formatted as YYYY/MM/DD
    return date("Y/m/d",$day);
}
?>
